const userManage = require('../module/userManage')
const jwt = require('../utils/jwt')

//登陆
const fn_login = async (ctx, next) => {
  //前端发送过来的数据
  const {
    userName,
    password
  } = ctx.request.body
  //新建对象 ， 根据传的不同的参数，生成不同的 token
  const token = new jwt({
    userName,
    password
  }).generateToken()
  //后端自己的数据
  if (userName === 'admin' && password === 'admin') {

    ctx.body = {
      code: 0,
      msg: '登陆成功！',
      data: {
        token
      }
    }
  } else {
    const resFinderUser = await userManage.findOne({
      userName
    })
    console.log(userName,'11',resFinderUser);
    if (resFinderUser !== null) {
      if (password === resFinderUser.password) {
        ctx.body = {
          code: 0,
          msg: '登陆成功',
          data: {
            token
          }
        }
      } else {
        ctx.body = {
          code: -1,
          msg: '密码错误'
        }
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '用户名不存在'
      }
    }
  }
};

//注册
const fn_register = async (ctx, next) => {
  //前端发送过来的数据
  const {
    userName,
    password
  } = ctx.request.body

  const resCreateUser = await userManage.create({
    userName,
    password
  })

  if (resCreateUser !== null) {
    ctx.body = {
      code: 0,
      msg: '注册成功',
      data: resCreateUser
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '注册失败',
      data: null
    }
  }
};




module.exports = {
  'POST /login': fn_login,
  'POST /register': fn_register
};